﻿using System;
using System.Windows.Forms;
using System.Xml;

namespace FileBrowser
{
    public partial class XmlViewerForm : Form
    {
        public XmlViewerForm()
        {
            InitializeComponent();
        }

        public void LoadXml(XmlDocument xmlDoc)
        {
            treeViewXml.Nodes.Clear();
            AddXmlNodeToTree(treeViewXml.Nodes, xmlDoc.DocumentElement);
            treeViewXml.ExpandAll();
        }

        private void AddXmlNodeToTree(TreeNodeCollection parentNodes, XmlNode xmlNode)
        {
            TreeNode treeNode = new TreeNode(xmlNode.Name);

            // 添加属性
            if (xmlNode.Attributes != null)
            {
                foreach (XmlAttribute attr in xmlNode.Attributes)
                {
                    TreeNode attrNode = new TreeNode($"@{attr.Name} = {attr.Value}");
                    attrNode.ForeColor = System.Drawing.Color.Blue;
                    treeNode.Nodes.Add(attrNode);
                }
            }

            // 添加子节点
            foreach (XmlNode childNode in xmlNode.ChildNodes)
            {
                if (childNode.NodeType == XmlNodeType.Element)
                {
                    AddXmlNodeToTree(treeNode.Nodes, childNode);
                }
                else if (childNode.NodeType == XmlNodeType.Text)
                {
                    TreeNode textNode = new TreeNode(childNode.Value);
                    textNode.ForeColor = System.Drawing.Color.Green;
                    treeNode.Nodes.Add(textNode);
                }
            }

            parentNodes.Add(treeNode);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            if (treeViewXml.SelectedNode != null)
            {
                Clipboard.SetText(treeViewXml.SelectedNode.Text);
            }
        }
    }
}